<template>
  <a-drawer
    title="付款申请"
    placement="right"
    :width="width"
    :closable="true"
    :visible="visible"
    :get-container="false"
    :wrap-style="{ position: 'absolute' }"
    :after-visible-change="afterVisibleChange"
    @close="close"
  >
    <div class="box" title="申请信息">
      <a-form-model
        style="margin:18px 10px 10px 10px"
        ref="ruleForm"
        :model="record"
        :rules="rules">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="结算单位" :labelCol="labelCol" :wrapperCol="wrapperCol">

              <a-input v-model="record.settlementCompany" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="付款单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="record.paySerial" disabled placeholder="提交后生成"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="付款申请人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="record.createBy" disabled></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="本位币金额" :labelCol="labelCol" :wrapperCol="wrapperCol">

              <a-input v-model="record.cnyAmount" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="付款金额" :labelCol="labelCol" :wrapperCol="wrapperCol">

              <a-input v-model="record.amount" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="开票状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag v-model="record.billStatus" placeholder="请选择发票状态" dictCode="kp_status" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="付款类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select v-model="record.payType" default-value="国内付款" allowClear style="width: 100%">
                <a-select-option value="国内付款">
                  国内付款
                </a-select-option>
                <a-select-option value="国外付款">
                  国外付款
                </a-select-option>
                <a-select-option value="代理付汇">
                  代理付汇
                </a-select-option>
                <a-select-option value="预付款">
                  预付款
                </a-select-option>
              </a-select>
              <!--              <j-dict-select-tag v-model="record.payType" placeholder="请选择付款方式" dictCode="pay_type" />-->
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="付款币种" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currency">
              <j-dict-select-tag v-model="record.currency" placeholder="请选择付款币种" dictCode="currency" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date style="width: 240px" v-model="record.createTime"></j-date>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="付款期限" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date style="width: 240px" v-model="record.payDate"></j-date>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="发票号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="record.invoiceNumber"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="汇率" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number style="width: 100%" v-model="rate" :precision="2" @change="changeanount"
                              :min="0.01"></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="备注" :labelCol="labelCol1" :wrapperCol="wrapperCol1">

              <a-input v-model="record.remark" type="textarea" :rows="4" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="申请事由" :labelCol="labelCol1" :wrapperCol="wrapperCol1">

              <a-input v-model="record.applyReason" type="textarea" :rows="4" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-tabs default-active-key="1">

        <a-button type="primary" slot="tabBarExtraContent" @click="gotoAdd" icon="plus">
          添加费用
        </a-button>
        <a-popconfirm style="margin-left: 8px" title="确定移除吗？" slot="tabBarExtraContent" @confirm="removedata">
          <a-button icon="close" type="danger" ghost>
            移除费用
          </a-button>
        </a-popconfirm>
        <!--        <a-button style="margin-left: 8px" @click="removedata">-->
        <!--         移除费用-->
        <!--        </a-button>-->
        <a-tab-pane key="1">
          <span slot="tab">
       费用明细
            <a style="color: red;margin-left: 8px;font-size: small">应付(CNY:{{ record.cnyAmount }})</a>
      </span>
          <j-vxe-table
            ref="addpayTable"
            row-selection
            resizable
            keep-source
            :loading="confirmLoading"
            :height="350"
            :dataSource="payList"
            :columns="payCol"
            style="margin-top: 8px;"
            @selectRowChange="handleSelectRowChange"
            :cell-style='cellStyle'
            bordered
          >
          </j-vxe-table>
        </a-tab-pane>
      </a-tabs>
    </a-spin>

    <div style="margin-top: 30px"></div>
    <div
      :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'left',
          zIndex: 999,
        }"
    >
      <a-button type="primary" @click="sumbit" icon="check">
        提交申请
      </a-button>
      <a-button :style="{ marginLeft: '8px' }" @click="close" icon="close">
        关闭
      </a-button>

    </div>
  </a-drawer>
</template>

<script>
import BillForm from '@/views/jzxtrade/modules/BillForm'
import { httpAction, getAction } from '@/api/manage'
import { ajaxGetDictItems } from '@api/api'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
import moment from 'moment'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import Vue from 'vue'
import { getDictItems } from '../../components/dict/JDictSelectUtil'
import { getDictItemsFromCache } from '../../api/api'
import { deleteAction, postAction } from '../../api/manage'

export default {

  name: 'ExpenseEntrySh',
  components: {
    JFormContainer,
    BillForm,
    JDate,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes
    }
  },
  props: {
    pay: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      rate: 1,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol1: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol1: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      width: '95%',
      Allfee: '1800',
      isedit: false,
      visible: true,
      selectedRowKeys: [],
      isdelete: false,
      payList: [],
      confirmLoading: false,
      modelId: '',
      record: {},
      CNYFee: '888',
      payCol: [
        {
          title: '费用状态',
          key: 'status',
          type: JVXETypes.normal,
          width: '200px',
          defaultValue: '录入状态'
        },
        {
          title: '费用名称',
          key: 'costName',
          type: JVXETypes.normal,
          width: '200px',
          align: 'center'
        },
        {
          title: '结算单位',
          key: 'settlementCompany',
          type: JVXETypes.normal,
          slotName: 'jsdw',
          width: '220px'
        },
        {
          title: '计费单位',
          key: 'chargingUnit',
          type: JVXETypes.normal,
          width: '180px'
        },

        {
          title: '币种',
          key: 'currency',
          type: JVXETypes.normal,
          width: '180px'
        },

        {
          title: '单价',
          key: 'price',
          type: JVXETypes.normal,
          width: '180px'
        },
        {
          title: '数量',
          key: 'num',
          type: JVXETypes.normal,
          width: '180px'

        },
        {
          title: '汇率',
          key: 'rate',
          type: JVXETypes.normal,
          width: '180px'
        },
        {
          title: '总价',
          key: 'totalPrice',
          type: JVXETypes.normal,
          width: '180px',
          defaultValue: '0'
          // statistics: ['sum']
        },
        // {
        //   title: '账单号',
        //   key: 'billNumber',
        //   type: JVXETypes.normal,
        //   width: '200px'
        // },
        {
          title: '发票号',
          key: 'invoiceNumber',
          type: JVXETypes.normal,
          width: '200px'
        },
        {
          title: '备注',
          key: 'remark',
          type: JVXETypes.normal,
          width: '200px'
        }
      ],
      rules: {
        rate: [{ required: true, message: '请填写汇率', trigger: 'change' }],
        currency: [{ required: true, message: '请选择币种', trigger: 'change' }]
      },
      url: {
        save: '/box.ship/shipInfo/cost/add',
        queryById: '/box.ship/shipInfo/cost/queryByShipId',
        deleteurl: '/box.ship/shipInfo/cost/del',
        submiturl: '/payapply/save',
        editurl: '/payapply/edit'
      },
      receiveCellEdit: true,
      // 选择的行
      selectedRows: [],
      //付款申请的业务类型 1：海运2：箱贸
      payApplyBuisType: 0
    }
  },
  computed: {},
  created() {
    this.initdata()
  },

  beforeCreate() {
    // this.form = this.$form.createForm(this, { name: 'dynamic_form_item' });
    // this.form.getFieldDecorator('boxType', { initialValue: [], preserve: true });

    // this.form.getFieldDecorator('keys', { initialValue: [], preserve: true });
  },
  methods: {
    initdata() {
      this.record.rate = 1
      // this.record.payDate = this.addDate()
      this.record.createTime = this.addDate()
    },
    //点击编辑进入的方法
    editAction(val) {
      this.record = val
      this.isedit = true
      //获取费用明细数据
      getAction('/payapply/query/costinfo', { id: this.record.id }).then(res => {
        if (res.success) {
          this.payList = res.result
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
      })
    },
    requestRecord(val) {
      let newlist = val
      for (let i = 0; i < newlist.length; i++) {
        for (let k = 0; k < this.payList.length; k++) {
          if (newlist[i].id === this.payList[k].id) {
            newlist.splice(newlist[i], 1)
          }
        }
      }

      let tempDataList = this.payList.concat(newlist)
      this.payList = tempDataList
      // this.payList.push(newlist[0])
      console.log(this.payList)

      if (this.payList.length > 0) {
        let allamount = 0
        for (let i = 0; i < this.payList.length; i++) {
          allamount += this.payList[i].totalPrice
        }
        console.log(allamount)
        this.record.amount = allamount
        this.record.cnyAmount = allamount
        this.record.settlementCompany = this.payList[0].settlementCompany
        //防止先填写汇率再选择数据
        this.changeanount()
      }
    },
    //获取当前年月日
    addDate() {
      const nowDate = new Date()
      const date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate()
      }
      const newmonth = date.month > 10 ? date.month : '0' + date.month
      const day = date.date > 10 ? date.date : '0' + date.date
      return date.year + '-' + newmonth + '-' + day

    },
    selectlist() {
      let param = { id: this.record.id }
      getAction(this.url.selecturl, param).then(res => {
        console.log(res)
        if (res.success) {
          this.payList = res.result
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
      })
    },
    // 当选择的行变化时触发的事件
    handleSelectRowChange(event) {
      this.selectedRows = event.selectedRows
    },
    cellStyle(row) {
      // console.log(row.row);
      if (row.row.scode == 2) {//判断条件，如果想要改变其他行样式，就写那一行的下标
        return `background-color: #fff1cf !important;color: #777777`
      } else {
        return `color: #777777`
      }
    },
    afterVisibleChange(val) {
      console.log('expenseVisible', val)
    },
    sumbit() {
      let ids = []
      if (this.payList.length == 0) {
        this.$message.warning('请添加费用明细')
        return
      } else {
        for (let i = 0; i < this.payList.length; i++) {
          ids.push(this.payList[i].id)
        }
        this.record.costIds = ids.toString()
      }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let url = ''
          if (this.isedit) {
            url = this.url.editurl
            let ids = []
            for (let i = 0; i < this.payList; i++) {
              ids.push(this.payList[i].id)
            }
            this.record.ids = ids
          } else {
            url = this.url.submiturl
          }
          this.record.rate = this.rate
          this.record.buisType = this.payApplyBuisType
          postAction(url, this.record).then(res => {
            console.log(res)
            if (res.success) {
              this.$message.success(res.message)
              this.close()
            } else {
              this.$message.warning(res.message)
            }
          }).finally(() => {

          })
        } else {

          return false
        }
      })
    },
    gotoAdd() {
      let val = this.record.settlementCompany
      this.$emit('gotoAdd', val)
    },
    removedata() {
      console.log(this.selectedRows.length)
      if (this.selectedRows.length > 0) {
        for (let i = 0; i < this.payList.length; i++) {
          for (let k = 0; k < this.selectedRows.length; k++) {
            if (this.payList[i].id === this.selectedRows[k].id) {
              this.payList.splice(this.payList[i], 1)
            }
          }
        }
        if (this.payList.length > 0) {
          let allamount = 0
          for (let i = 0; i < this.payList.length; i++) {
            allamount += this.payList[i].totalPrice
          }
          console.log(allamount)
          this.record.amount = allamount
          this.record.cnyAmount = allamount
          //防止先填写汇率再选择数据
          this.changeanount()
        }
      } else {
        this.$message.warning('请勾选数据')
      }

    },
    close() {
      console.log('close')
      this.$emit('close')
      // this.visible = false
    },
    changeanount() {
      this.record.cnyAmount = parseFloat(this.record.amount * this.rate).toFixed(2)
    }
  }
}

</script>

<style scoped>
.box {
  position: relative;
  border: 1px solid #e8e8e8;
}

.box::before {
  content: attr(title);
  position: absolute;
  left: 5%;
  transform: translateX(-50%);
  -webkit-transform: translate(-50%, -50%);
  padding: 0 10px;
  background-color: #fff;
}

/deep/ .ant-form-item {
  margin-bottom: 0px;
}
</style>